package cn.wolfcode.business.category.service.impl;

import java.util.*;

import cn.wolfcode.business.category.domain.BusCategory;
import cn.wolfcode.business.category.domain.vo.BusCategoryParentVO;
import cn.wolfcode.common.core.domain.entity.SysDept;
import cn.wolfcode.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.wolfcode.business.category.mapper.BusCategoryMapper;
import cn.wolfcode.business.category.service.IBusCategoryService;
import org.springframework.util.Assert;

/**
 * 分类管理Service业务层处理
 *
 * @author Mbester
 * @date 2023-06-16
 */
@Service
public class BusCategoryServiceImpl implements IBusCategoryService {
    @Autowired
    private BusCategoryMapper busCategoryMapper;

    /**
     * 查询分类管理
     *
     * @param id 分类管理主键
     * @return 分类管理
     */
    @Override
    public BusCategoryParentVO selectBusCategoryById(Long id) {
        Assert.notNull(id, "参数异常");
        BusCategory busCategory = busCategoryMapper.selectBusCategoryById(id);
        Assert.notNull(busCategory, "参数异常");

        BusCategoryParentVO busCategoryParentVO = new BusCategoryParentVO();
        busCategoryParentVO.setId(busCategory.getId());
        busCategoryParentVO.setName(busCategory.getName());
        busCategoryParentVO.setParentId(busCategory.getParentId());
//        busCategoryParentVO.setParentName(busCategory.getParentName());
        return busCategoryParentVO;
    }

    /**
     * 查询分类管理列表
     *
     * @param busCategory 分类管理
     * @return 分类管理
     */
    @Override
    public List<BusCategory> selectBusCategoryList(BusCategory busCategory) {


        return busCategoryMapper.selectBusCategoryList(busCategory);
    }

    /**
     * 新增分类管理
     *
     * @param busCategory 分类管理
     * @return 结果
     */
    @Override
    public Long insertBusCategory(BusCategory busCategory) {
        Assert.notNull(busCategory, "参数异常");
        BusCategory category = busCategoryMapper.selectBusCategoryByName(busCategory.getName());
        if (category != null) {
            throw new RuntimeException("分类名称重复");
        }

        BusCategory parent = busCategoryMapper.selectBusCategoryById(busCategory.getParentId());
        if (parent != null) {
            busCategory.setParentName(parent.getName());
            busCategoryMapper.insertBusCategory(busCategory);
            busCategory.setPath(parent.getPath() + ":" + busCategory.getId().toString());
            busCategoryMapper.updateBusCategory(busCategory);
            return busCategory.getId();
        } else {
            busCategoryMapper.insertBusCategory(busCategory);
            busCategory.setPath(busCategory.getId().toString());
            busCategoryMapper.updateBusCategory(busCategory);
            return busCategory.getId();
        }
    }

    /**
     * 修改分类管理
     *
     * @param busCategory 分类管理
     * @return 结果
     */
    @Override
    public int updateBusCategory(BusCategory busCategory) {
        // 参数判空和查重
        Assert.notNull(busCategory, "参数异常");
        BusCategory category = busCategoryMapper.selectBusCategoryById(busCategory.getId());
        Assert.notNull(category, "参数异常");
        if ((category.getName().equals(busCategory.getName()))
                && category.getParentId().equals(busCategory.getParentId())) {
            throw new RuntimeException("分类名称重复");
        }


        if (busCategory.getParentId() != null) {
            BusCategory parent = busCategoryMapper.selectBusCategoryById(busCategory.getParentId());
            Assert.notNull(parent, "参数异常");

            busCategory.setParentId(parent.getId());
            busCategory.setParentName(parent.getName());
            busCategory.setPath(parent.getPath() + ":" + busCategory.getId().toString());
//            busCategory.setParentName(parent.getName());
        } else {
            busCategory.setParentId(null);
            busCategory.setParentName(null);
            busCategory.setPath(busCategory.getId().toString());
        }
        return busCategoryMapper.updateBusCategory(busCategory);
    }

    /**
     * 批量删除分类管理
     *
     * @param ids 需要删除的分类管理主键
     * @return 结果
     */
    @Override
    public int deleteBusCategoryByIds(Long[] ids) {
        return busCategoryMapper.deleteBusCategoryByIds(ids);
    }

    /**
     * 删除分类管理信息
     *
     * @param id 分类管理主键
     * @return 结果
     */
    @Override
    public int deleteBusCategoryById(Long id) {
        return busCategoryMapper.deleteBusCategoryById(id);
    }

    /**
     * 获取上级分类名称
     *
     * @return
     */
    @Override
    public List<BusCategoryParentVO> getParentNames() {
        List<BusCategoryParentVO> parentNames = busCategoryMapper.getParentNames();
        return parentNames;
    }

    /**
     * 获取上级分类选项
     *
     * @return
     */
    @Override
    public List<BusCategory> getOptions() {
        List<BusCategory> AllList = busCategoryMapper.selectAllList();
        List<BusCategory> returnList = new ArrayList<>();
        List<Long> tempList = new ArrayList<Long>();

        for (BusCategory busCategory : AllList) {
            tempList.add(busCategory.getId());
        }

        for (BusCategory busCategory : AllList) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(busCategory.getParentId())){
                recursionFn(AllList, busCategory);
                returnList.add(busCategory);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = AllList;
        }

        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<BusCategory> list, BusCategory t)
    {
        // 得到子节点列表
        List<BusCategory> childList = getChildList(list, t);
        t.setChildren(childList);
        for (BusCategory tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<BusCategory> list, BusCategory t)
    {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 得到子节点列表
     */
    private List<BusCategory> getChildList(List<BusCategory> list, BusCategory t)
    {
        List<BusCategory> tlist = new ArrayList<BusCategory>();
        Iterator<BusCategory> it = list.iterator();
        while (it.hasNext())
        {
            BusCategory n = (BusCategory) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue())

            {
                tlist.add(n);
            }
        }
        return tlist;
    }


    public List<BusCategory> getChildren(List<BusCategory> children) {
        List<BusCategory> categories = new ArrayList<>();
        List<BusCategory> categories2 = new ArrayList<>();

        for (BusCategory child : children) {
            String[] paths = child.getPath().split(":");
            if (paths.length == 1) {
                BusCategory busCategory = busCategoryMapper.selectBusCategoryById(Long.parseLong(paths[0]));
                busCategory.setChildren(null);
                categories.add(busCategory);
            } else if (paths.length >= 2) {
                BusCategory busCategory = busCategoryMapper.selectBusCategoryById(Long.parseLong(paths[0]));
                List<String> list = new ArrayList<>(Arrays.asList(paths));
                list.remove(0);

                List<BusCategory> childrenList = busCategoryMapper.selectBusCategoryByIds(list);
                if (childrenList.size() > 1) {
                    List<BusCategory> childrens = getChildren(childrenList);
                    busCategory.setChildren(childrens);
                } else {
                    busCategory.setChildren(null);
                };
                categories2.add(busCategory);
            }

        }


        for (BusCategory category : categories) {
            for (BusCategory busCategory : categories2) {
                if(category.getId().equals(busCategory.getParentId())) {
                    category.getChildren().add(new BusCategory(busCategory.getId(),busCategory.getName(),busCategory.getChildren()));
                }
            }
        }

        return categories;
    }
}
